<html>
  <head></head>
  <body>
    <div id="game"></div>
    <p>Once your mouse hovers over the object, it will start moving. Make sure to follow it with your mouse pointer!</p>
    <script src="https://cdn.rawgit.com/craftyjs/Crafty/release/dist/crafty-min.js"></script>
    <script>
        Crafty.init(600, 600, document.getElementById('game'));
        Crafty.background('rgb(127,127,127)');

        var started = false;

        Crafty.e("2D, DOM, Color, Keyboard, Mouse, Motion")
            .attr({
                x: Crafty.viewport._width / 2 - 32, w: 64,
                y: Crafty.viewport._height / 2 - 32, h: 64,
                lastMoveDT: 0 
            })
            .color('blue')
            .bind('Moved', function() {
                if (this.x < 0) {
                    this.vx = Crafty.math.abs(this.vx);
                } else if (this.x + this.w > Crafty.viewport._width) {
                    this.vx = -Crafty.math.abs(this.vx);
                }

                if (this.y < 0) {
                    this.vy = Crafty.math.abs(this.vy);
                } else if (this.y + this.h > Crafty.viewport._height) {
                    this.vy = -Crafty.math.abs(this.vy);
                }
            })
            .bind('EnterFrame', function(frame) {
                if (this.lastMoveDT > Crafty.math.randomInt(1000, 3000)) {
                    this.vx = Crafty.math.randomInt(-150, 150);
                    this.vy = Crafty.math.randomInt(-150, 150);
                    this.lastMoveDT = 0;
                }
                this.lastMoveDT += frame.dt;
            })
            .bind('MouseOver', function() {
                this.lockKeyboard();
                started = true;
            })
            .bind('MouseOut', function() {
                this.releaseKeyboard();
            });


        Crafty.s("HotWire", {
            events: {
                "EnterFrame": function() {
                    if (started && Crafty.s('Keyboard').lockKeyboard(this)) {
                        alert('Kaboom!');
                    }
                }
            }
        }, {}, false);
    </script>
  </body>
</html>
